package cn.wolfcode.crm.serivce.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.mapper.MenuMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.serivce.IMenuService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;


@Service
public class MenuServiceImpl implements IMenuService {
    @Autowired
    private MenuMapper mapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(Menu record) {
        if (record.getId() == null) {
            //保存操作
            mapper.insert(record);
        }else {
            mapper.updateByPrimaryKey(record);
        }
    }

    @Override
    public Menu selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult query(QueryObject qo) {

//        Integer total = mapper.count(qo);
//        if (total > 0) {
//            List<Menu> rows = mapper.query(qo);
//
//            return new PageResult(total,rows);
//        }
//        return new PageResult(0, Collections.EMPTY_LIST);
        return null;
    }

    @Override
    public List<Menu> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public List<Menu> selectRootMenu() {
        return mapper.selectRootMenu();
    }

    @Override
    public List<Long> selectByRoleId(Long roleId) {
        return mapper.selectByRoleId(roleId);
    }

    /**
     * 实现不同员工有不同的菜单方法
     * 在service中实现,避免sql中麻烦的查询(由于菜单结构的特殊children集合结果)
     * @return
     */
    @Override
    public List<Menu> selectEmployeeMenu() {
        //1.获取所有的菜单
        List<Menu> menus = mapper.selectRootMenu();
        //2.获取当前用户所拥有的id集合
        Employee employee = UserContext.getCurrentuser();
        //判断是否是超级管理员
        if (!employee.getAdmin()) {
            //获取当前用户菜单的id集合
            List<Long> menuids = mapper.selectByEmployeeId(employee.getId());
            //调用检查权限
            checkPermission(menus,menuids);
        }

        return menus;
    }
    public void checkPermission(List<Menu> menus,List<Long> ids){
        //2.遍历菜单当前用户没有权限的移除掉菜单
        Iterator<Menu> iterator = menus.iterator();
        while (iterator.hasNext()){
            Menu menu = iterator.next();
            //当员工的菜单id集合中不能存在这个菜单的id,删除掉
            if (!ids.contains(menu.getId())) {
                iterator.remove();
            }
            //递归判断:当前菜单如果有子菜单(children)那么久递归
            if (menu.getChildren().size()>0) {
                checkPermission(menu.getChildren(),ids);
            }

        }
    }
}
